﻿@model IEnumerable<App.Web.ViewModels.ProductImageViewModel>
@using App.Web.Utility;
@using App.Core.Extensions;
@using App.Core.DB;
@using App.Web.ViewModels;

@{
    Layout = "~/Views/Shared/_PopupLayout.cshtml";
    ViewBag.Title = Html.GetPageTitle("Add Remove Product Images");
    int _ProductID = ViewBag.ProductID;
    int _ProductImageID = Convert.ToInt32(ViewBag.ProductImageID);
    ProductViewModel product = ViewBag.Product as ProductViewModel;
    String _Info = product == null ? String.Empty : product.Name;
    String _TempUploadedImageUrl = ViewBag.CropBoxImageUrl;// == null ? String.Empty : NullHandler.GetString(ViewBag.CropBoxImageUrl);
}
<div class="page-heading" style="padding-top:0px; padding-left:0px; margin-bottom:0px;">
    <h1>Manage Product Images</h1>
    <div>
        You can upload maximum @ConfigReader.MaxNumberOfProductImages images for @_Info.        
    </div>
</div>
<div>
    @if (product == null)
    {
        @Html.ErrorMessageBox("Sorry! Requested Product does not exist.")
    }
    else
    {   
        <table cellpadding="0" cellspacing="0" style="border-collapse:collapse; width:881px;">
            <colgroup>
                <col style="width:133px;" />
                <col style="width:543px;" />
                <col style="width:205px;" />
            </colgroup>

            <tr>
                @*Left Column*@
                <td class="border-right" style="vertical-align:top; padding:5px 5px 0px 0px;">
                    <div id="divThumbContainer">
                    @foreach (App.Web.ViewModels.ProductImageViewModel image in Model)
                    {
                        <div class="crop-product-thumb">
                            <a href="javascript:void(0);" onclick="ConformDeleteDialog(@image.ID, this);" title="Click to Delete this Product Image.">
                                @Html.ProductThumb(image, this.Url, "Click to Delete this Product Image.")
                            </a>
                        </div>
                    }
                    </div>
                    <div id="divPosition"></div>
                </td>

                @*Middle Column*@
                <td class="border-right" style="vertical-align:top;  padding:5px 5px 0px 5px;">
                    <div style="min-height:330px;">
                    <form id="frmProductImage" action="@Url.Action("List")" method="post" enctype="multipart/form-data">            
                        <div>
                            <table cellpadding="3" cellspacing="0" style="width:100%; border-collapse:collapse;">                                
                                <tr id="trUploadControls" @{if (!_TempUploadedImageUrl.IsNullOrEmpty()) { <text> style="display:none;"</text>}}>
                                    <td style="width:160px;">Select an Image to Upload</td>
                                    <td><input type="file" id="fileProductImage" onchange="ValidateUpload();" name="productImage" /></td>
                                    @*<td><input type="submit" value="Upload" onclick="return ValidateUpload();" /></td>*@
                                </tr>                                
                            </table>
                            @if (ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] != null){
                                @Html.ErrorMessageBox(ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] as String)    
                            }
                            <input type="hidden" name="hdnWidthHeight" id="hdnWidthHeight" value="@ViewBag.WidthHeight" />
                            <input type="hidden" name="productID" id="productID" value="@_ProductID" />
                            <input type="hidden" id="hdnCoordinates" value="" />
                            <input type="hidden" id="hdnProductImageID" name="productImageID" value="@_ProductImageID" />
                            <input type="hidden" id="hdnOriginalFileName" value="@ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME]" />
                        </div>   
                        <div class="cropbox">
                            <div id="divCropBoxContainer" class="cropbox">                    
                                <img id="imgCropBox" src="@_TempUploadedImageUrl" alt="" @{if (_TempUploadedImageUrl.IsNullOrEmpty()){ <text>style="display:none;"</text>}}/>
                            </div>
                        @if (!_TempUploadedImageUrl.IsNullOrEmpty()){
                            <div id="divButtons" style="margin-top:5px;">
                                <input id="btnSave" type="button" value="Save" onclick="CropAndSaveImage();" />
                                <input id="btnCancel" type="button" value="Cancel" onclick="CancelImageCrop();" />
                            </div>
                        }
                        </div>
                    </form>     
                    </div>               
                </td>
                @*Right Column*@
                <td style="vertical-align:top; padding:5px 0px 0px 5px;">
                    <div class="thumbContainer" style="overflow: hidden; width:200px; height:150px;">
                        <img id="imgPreview" class="jcrop-preview" src="@ViewBag.CropBoxImageUrl" alt="" />
                    </div>
                </td>
            </tr>
        </table>
        
        <div id="dialog" style="display:none;"></div>
        <div id="deleteDialog" style="display:none;">Do you really want to Delete this Product Image?</div>
        
        <script language="Javascript" type="text/javascript">
            var _ProductID = @_ProductID;        
            $(document).ready(function(){
                BindImageCropper();
                $('#dialog').dialog({
                    autoOpen: false, width: 400,
                    buttons: {
                        "Ok": function () { $(this).dialog("close"); }
                    }
                });
                $('#deleteDialog').dialog({
                    autoOpen: false, width: 400,
                    buttons: {
                        'Ok': function () { ShowLoadingAnimation(false); DeleteImage(); $(this).dialog("close"); },
                        'Cancel' : function() { $(this).dialog("close"); }
                    }
                });
                parent.ChildHideLoading();
            });
            
            function SetCoordinates(c) {        
                $('#hdnCoordinates').val(c.x + ',' + c.y + ',' + c.w + ',' + c.h );
            }
            var _jCropApi;
            var _ActualWidth = 0;
            var _ActualHeight = 0;
            function BindImageCropper() {
                var widthAndHeight = $('#hdnWidthHeight').val();
                if(widthAndHeight.length > 0)
                {
                    if (_jCropApi) _jCropApi.destroy();
                    $('#imgCropBox').Jcrop({
                        setSelect: [0, 0, 200, 150],
                        onChange: ShowPreview,
                        onSelect: ShowPreview,
                        aspectRatio: @ConfigReader.ProductImageAspectRatio //1.33
                    }, function () {
                        _ActualWidth = widthAndHeight.split(',')[0];
                        _ActualHeight = widthAndHeight.split(',')[1];
                        _jCropApi = this;
                        parent.AdjustiFrameHeight($(document).height());
                    });
                }
                else
                    parent.AdjustiFrameHeight($(document).height());
            }  

            function ShowPreview(coords) {
                SetCoordinates(coords);
                if (parseInt(coords.w) > 0 && _ActualWidth > 0 && _ActualHeight > 0) {
                    var rx = 200 / coords.w;
                    var ry = 150 / coords.h;

                    $('#imgPreview').css({
                        width: Math.round(rx * _ActualWidth) + 'px',
                        height: Math.round(ry * _ActualHeight) + 'px',
                        marginLeft: '-' + Math.round(rx * coords.x) + 'px',
                        marginTop: '-' + Math.round(ry * coords.y) + 'px'
                    });
                }
            }
            function CropAndSaveImage() {             
                var coordinates =  $('#hdnCoordinates').val();
                if(coordinates.length > 0)
                {
                    var url = '@Url.Action("CropAndSaveImage", "ProductImage", new { area = AppConstants.Area.PRIVATE })';
                    var data = { ID: $('#hdnProductImageID').val(), ProductID: _ProductID, Picture: $('#imgCropBox').attr('src'), CropProperty: coordinates, OriginalFileName: $('#hdnOriginalFileName').val() }; //imageJson, //$.toJSON(image), //'fileName=Hydrangeas.jpg&cropProperty=' + $('#hdnCoordinates').val();
                    ShowLoadingAnimation(false);
                    Ajax(url, data, CropAndSaveImage_Success);                    
                }
                else
                   $('#dialog').html('Please Select and Upload an Image first to Set it as a Product Image.').dialog('open'); //alert("Please Select and Upload an Image first to Set it as a Product Image."); 
            }
            function CropAndSaveImage_Success(obj){
                HideLoadingAnimation();
                var image = eval(obj);
                $('#divCropBoxContainer').hide();
                $('#imgPreview').hide();
                $('#btnSave').attr('disabled', true);   
                    
                var html = '<div class="crop-product-thumb">' +
                                '<a href="javascript:void(0);" onclick="ConformDeleteDialog(' + image.ID + ', this);" title="Click to Delete this Product Image.">' + 
                                    '<img src="' + image.Thumbnail + '" alt="" title="" />' + 
                                '</a>' + 
                            '</div>';
                $('#divThumbContainer').append(html);
                $('#trUploadControls').slideDown('slow');
                $('#divButtons').fadeOut('slow');
                parent.UpdateImageList(image.Thumbnail, image.Picture);
                parent.AdjustiFrameHeight('iframeImageList');
            }
            function CancelImageCrop()
            {
                $('#divCropBoxContainer').slideUp('slow');
                $('#trUploadControls').slideDown('slow');                
                $('#divButtons').fadeOut('slow');
                $('#imgPreview').fadeOut('slow');
                $('#hdnCoordinates').val('');
            }
            var _AnchorToDelete = null;
            var _ImageIdToDelete = 0;
            function ConformDeleteDialog(imageId, anchorElement) {
                _ImageIdToDelete = imageId;
                _AnchorToDelete = anchorElement;
                $('#deleteDialog').dialog('open');
            }
            function DeleteImage() {                
                var url = '@Url.Action("DeleteProductImage", "ProductImage", new { area = AppConstants.Area.PRIVATE })';
                var data = 'imageId=' + _ImageIdToDelete;
                Ajax(url, data, Delete_Success);                                
            }
            function Delete_Success(isDeleted) {
                if(isDeleted){
                    var thumbUrl = $(_AnchorToDelete).find('img').attr('src');
                    $(_AnchorToDelete).parent().remove();                    
                    $('#dialog').html('Product Image Deleted Successfully.').dialog('open');//alert("Product Image Deleted Successfully.");
                    setTimeout(function () { $('#dialog').dialog('close'); }, 3000);
                    parent.AdjustiFrameHeight('iframeImageList');
                    parent.DeleteFromImageList(thumbUrl);
                }
                else
                    $('#dialog').html('Sorry! Requested Image was not found for Delete.').dialog('open');//alert("Sorry! Requested Image was not found for Delete.");
                HideLoadingAnimation();
            }
            function ValidateUpload() {
                if($('#fileProductImage').val().length > 0){
                    ShowLoadingAnimation(false);
                    $('#frmProductImage').submit();
                }
                else
                    return false;
                return true;
            }
        </script>
    }    
</div>


